package lifeed;

import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.net.URL;
import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import org.dom4j.Element;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.dom4j.DocumentException;

public class FeedRSS {
    
    private String title = "";
    private String description = "";
    private String link = "";
    private Date lastBuildDate = new Date();

    private List<ItemRSS> items = null;    // Gli item appartenenti al podcast
    
    private Document document = null;   // Documento DOM con la struttura del FeedRSS
    
    public FeedRSS(String sourcePath) throws DocumentException, java.net.MalformedURLException {
        SAXReader reader = new SAXReader();
        
        // Impostazione del documento da parsificare
        if (sourcePath.indexOf("://") > -1)
            document = reader.read(new URL(sourcePath));
        else document = reader.read(new File(sourcePath));
        parseDocument();
    }

    public FeedRSS(String sourcePath, Date lastDate) throws DocumentException, java.net.MalformedURLException {
        SAXReader reader = new SAXReader();

        // Impostazione del documento da parsificare
        if (sourcePath.indexOf("://") > -1)
            document = reader.read(new URL(sourcePath));
        else document = reader.read(new File(sourcePath));
        parseDocument();
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Document getDocument() {
        return document;
    }

    public void setDocument(Document document) {
        this.document = document;
    }

    public List<ItemRSS> getItems() {
        return items;
    }

    public void setItems(List<ItemRSS> items) {
        this.items = items;
    }

    public Date getLastBuildDate() {
        return lastBuildDate;
    }

    public void setLastBuildDate(Date lastBuildDate) {
        this.lastBuildDate = lastBuildDate;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
        
    @Override
    public String toString() {
        String buffer = "TITLE: " + title;
        buffer += "\nLINK: " + link;
        buffer += "\nDESCRIPTION: " + description;
        buffer += "\nLASTBUILDDATE: " + lastBuildDate.toString();
        
        return buffer;
    }

    // ### METODI PRIVATI ###
    private void parseDocument() throws DocumentException {
        Element channel = document.getRootElement().element("channel");
        
        // Parsing elementi della specifica RSS 2.0
        this.title = channel.element("title") != null ? channel.element("title").getText() : "";
        this.link = channel.element("link") != null ? channel.element("link").getText() : "";
        this.lastBuildDate = channel.element("lastBuildDate") != null ? parseDate(channel.element("lastBuildDate").getText()) : new Date();
        this.description = channel.element("description") != null ? channel.element("description").getText() : "";
        
        // Elaborazione degli items
        items = new LinkedList();
        Iterator itItems = channel.elementIterator("item");
        while (itItems.hasNext()) {
            Element itemElement = (Element) itItems.next();
            items.add(new ItemRSS(itemElement));

        }
    }

	public Date parseDate(String d) {
        String[] date_formats = { "yyyy-MM-dd'T'kk:mm:ss'Z'", // ISO
			"yyyy-MM-dd'T'kk:mm:ssz", // ISO
			"yyyy-MM-dd'T'kk:mm:ss", // ISO
			"EEE, dd MMM yy HH:mm:ss z", // RFC822
			"EEE, d MMM yyyy kk:mm:ss z", // RFC2882
			"EEE MMM  d kk:mm:ss zzz yyyy", // ASC
			"EEE, dd MMMM yyyy kk:mm:ss", // Disney Mon, 26 January 2004
											// 16:31:00 ET
			"yyyy-MM-dd kk:mm:ss.0", "-yy-MM", "-yyMM", "yy-MM-dd",
			"yyyy-MM-dd", "yyyy-MM", "yyyy-D", "-yyMM", "yyyyMMdd", "yyMMdd",
			"yyyy", "yyD"

        };
        Date date = null;
		SimpleDateFormat formatter;
		d = d.replaceAll("([-+]\\d\\d:\\d\\d)", "GMT$1"); // Correct W3C times
		d = d.replaceAll(" ([ACEMP])T$", " $1ST"); // Correct Disney times
		for (int i = 0; i < date_formats.length; i++) {
			try {
				formatter = new SimpleDateFormat(date_formats[i], Locale.ENGLISH);
				date = formatter.parse(d);
				break;
			} catch (Exception e) {}
		}

		return date;
	}
}